<template>
  <section>
    <van-notify v-model:show="peerStore.activateNotification" background="rgb(0,0,0,.7)">
      <section>
        <section>
          您好，目前有一位求助者正在寻求您的协助。请问您能否提供帮助？
        </section>

        <van-divider />

        <section>
          <van-button type="primary" size="small" @click="acceptVideoCall">
            接受
          </van-button>

          <van-divider vertical />

          <van-button type="danger" size="small" @click="rejectVideoCall">
            拒绝
          </van-button>
        </section>
      </section>

    </van-notify>
  </section>

  <section>
    <router-view v-slot="{ Component }">
      <keep-alive include="CommunicationView,SettingsView">
        <component :is="Component" />
      </keep-alive>
    </router-view>
  </section>
</template>

<script>
export default {
  name: "MainEntranceView"
}
</script>

<script setup>
import { watch } from "vue";
import { showLoadingToast } from "vant";
import { useRouter } from "vue-router";
import usePeerStore from "@/store/peer";
import useVideoCallMatchStore from "../../store/user/VideoCallMatch";

let matchStore = useVideoCallMatchStore();
let peerStore = usePeerStore();
let router = useRouter();

function rejectVideoCall() {
  peerStore.dataConnection.send({
    instruction: peerStore.instruction.reject
  });
  peerStore.dataConnection = undefined;
  peerStore.activateNotification = false;

  releaseMatch()
}

// 志愿者放弃了，也得把自己释放掉
function releaseMatch() {
  matchStore.videoCallAttr.socket.send(JSON.stringify({
    message: 'endMatch',
    volPeerId: matchStore.videoCallAttr.peerId
  }))
}

function acceptVideoCall() {
  peerStore.activateNotification = false;

  let loadingToast = showLoadingToast({
    duration: 0,
    forbidClick: true,
    loadingType: "spinner",
    message: "连接中，请稍后..."
  });

  //监听媒体连接是否存在，有可能速度比较快，所以立即执行以下
  let cancel = watch(() => peerStore.mediaConnection, newValue => {
    if (newValue) {
      //关闭加载框
      loadingToast.close();

      //取消监听；如果不取消会出现重复执行
      cancel();

      router.push({
        path: "/video-call-answer-view"
      });
    }
  }, { immediate: true });

  peerStore.dataConnection.send({
    instruction: peerStore.instruction.accept
  });

}
</script>